package com.ark.utils;

import com.google.gson.Gson;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.entity.UrlEncodedFormEntity;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ContentType;
import org.apache.hc.core5.http.NameValuePair;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;
import org.apache.hc.core5.http.message.BasicNameValuePair;
import org.apache.hc.core5.net.URIBuilder;

import java.net.URI;
import java.util.ArrayList;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * Http工具类
 */
public class HttpClientUtil {
    static final long TIMEOUT = 5;

    /**
     * 发送get请求
     * @param url 请求url
     * @param paramMap 请求参数
     * @return 响应结果
     */
    public static String doGet(String url, Map<String,String> paramMap){
        try (CloseableHttpClient httpClient = HttpClients.createDefault()){
            URIBuilder builder = new URIBuilder(url);

            if(paramMap != null){
                paramMap.forEach(builder::addParameter);
            }
            URI uri = builder.build();

            HttpGet httpGet = new HttpGet(uri);
            return httpClient.execute(httpGet, response -> {
                String result = "";
                if (response.getCode() == 200) {
                    result = EntityUtils.toString(response.getEntity());
                }
                return result;
            });
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    /**
     * 发送post请求
     * @param url 请求url
     * @param paramMap 请求体
     * @return 响应信息
     */
    public static String doPost(String url, Map<String,String> paramMap) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()){
            //参数列表
            HttpPost httpPost = new HttpPost(url);
            if(paramMap != null){
                ArrayList<NameValuePair> paramList = new ArrayList<>();
                for (Map.Entry<String, String> entry : paramMap.entrySet()) {
                    paramList.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                //模拟表单
                UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
                httpPost.setEntity(entity);
            }
            httpPost.setConfig(buildRequestConfig());
            //执行http请求
            return httpClient.execute(httpPost,response-> EntityUtils.toString(response.getEntity()));
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    public static String doPost4Json(String url, Map<String,String> paramMap) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()){
            HttpPost httpPost = new HttpPost(url);

            if(paramMap != null){
                //构建json格式数据
                Gson gson = new Gson();
                String json = gson.toJson(paramMap);
                StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
                httpPost.setEntity(entity);
            }
            httpPost.setConfig(buildRequestConfig());
            return httpClient.execute(httpPost,response-> EntityUtils.toString(response.getEntity()));
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }

    private static RequestConfig buildRequestConfig() {
        return RequestConfig.custom()
                .setConnectionRequestTimeout(TIMEOUT,TimeUnit.SECONDS)
                .build();
    }
}
